package com.cy.impl;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NoticeJdbcDaoImpl2 implements NoticeJdbcDao{

    private DataSource dataSource;

    @Override
    public void insertNotice(String sql, Object[] values) throws SQLException {
        Connection connection = dataSource.getConnection();
        PreparedStatement statement =  connection.prepareStatement(sql);
        for (int i = 0; i < values.length; i++) {
            statement.setObject(i,values[i]);
        }

        statement.execute();
        connection.close();
        statement.close();
    }

    @Override
    public List<Map<String, Object>> selectNotices(String sql, Object[] values) throws SQLException {
        Connection connection = dataSource.getConnection();
        PreparedStatement statement = connection.prepareStatement(sql);
        for (int i = 0; i < values.length; i++) {
            statement.setObject(i,values[i]);
        }

        boolean flag = statement.execute();
        ResultSet result;
        List<Map<String,Object>> list = new ArrayList<>();
        if (flag){
            result = statement.getResultSet();
            ResultSetMetaData rsmd = result.getMetaData();
            while (result.next()){
                Map<String,Object> map  = new HashMap<>();
                for (int i=1;i<rsmd.getColumnCount();i++){
                    map.put(rsmd.getColumnLabel(i),result.getObject(rsmd.getColumnLabel(i)));
                }
                System.out.println(map);
                list.add(map);
            }

        }
        statement.execute();
        connection.close();
        statement.close();
        return list;
    }

    @Override
    public void update(String sql, Object[] values) throws SQLException {
        Connection conn = dataSource.getConnection();
        PreparedStatement pstm = conn.prepareStatement(sql);
        for (int i=0;i<values.length;i++){
            pstm.setObject(i,values[i]);
        }

        pstm.execute();
        conn.close();
        pstm.close();

    }
}
